package robot

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type FeishuRichTextRobot struct {
	// 发送富文本,格式如下
	//[{
	//	"tag": "text",
	//	"text": "项目有更新: "
	//	},
	//	{
	//	"tag": "a",
	//	"text": "请查看",
	//	"href": "http://www.example.com/"
	//	},
	//	{
	//	"tag": "at",
	//	"user_id": "ou_18eac8********17ad4f02e8bbbb"
	//	}
	//]
	Webhook  string
	Content  [][]map[string]string
	Language string
	Title    string
}

func (receiver FeishuRichTextRobot) Send() {
	data := make(map[string]interface{})
	data["msg_type"] = "post"
	data["content"] = map[string]interface{}{
		"post": map[string]interface{}{
			receiver.Language: map[string]interface{}{
				"title":   receiver.Title,
				"content": receiver.Content,
			},
		},
	}
	bdata,_ := json.Marshal(data)
	reader := bytes.NewReader(bdata)
	req, err := http.NewRequest("POST", receiver.Webhook, reader)

	if err == nil {
		client := http.Client{}
		response, err := client.Do(req)

		if err == nil {
			defer response.Body.Close()
			body, err := ioutil.ReadAll(response.Body)
			if err != nil {
				fmt.Println(err)
			} else {
				fmt.Println(string(body))
			}
		}
	}
}

func NewFeishuRichTextRobot() *FeishuRichTextRobot {
	return &FeishuRichTextRobot{
		Webhook:  "",
		Content:  nil,
		Language: "zh_cn",
		Title:    "",
	}
}
